package _04file

import groovy.util.slurpersupport.GPathResult
import groovy.xml.MarkupBuilder

/*
解析xml
 */

final String xml = '''
    <response version-api="2.0">
        <value>
            <books id="1" classification="android">
                <book available="20" id="1">
                    <title>疯狂Android讲义</title>
                    <author id="1">李刚</author>
                </book>
                <book available="14" id="2">
                   <title>第一行代码</title>
                   <author id="2">郭林</author>
               </book>
               <book available="13" id="3">
                   <title>Android开发艺术探索</title>
                   <author id="3">任玉刚</author>
               </book>
               <book available="5" id="4">
                   <title>Android源码设计模式</title>
                   <author id="4">何红辉</author>
               </book>
           </books>
           <books id="2" classification="web">
               <book available="10" id="1">
                   <title>Vue从入门到精通</title>
                   <author id="4">李刚</author>
               </book>
           </books>
       </value>
    </response>
'''

//解析xml
def slurper = new XmlSlurper()
def response = slurper.parseText(xml)//返回根节点
println response.value.books[0].book[0].title.text()//获取第一本书的title
println response.@'version-api'//获取属性

def booklist = []
//遍历查找所有作者为李刚的数
response.value.books.each { books ->
    //对books下的book集合进行遍历
    books.book.each { book ->
        if (book.author.text().equals('李刚')) {
            booklist.add(book.title.text())
        }
    }
}
println booklist.toListString()

//除了以上的普通遍历，Groovy还为我们提供了深度、广度遍历
//深度遍历所有作者为李刚的书
def all = response.depthFirst().findAll { book ->
    return book.author.text() == '李刚'
}
println all

//广度遍历节点为book id为2的书
def collect = response.value.books.children().findAll { node ->
    node.name() == 'book' && node.@id == '2'
}.collect { node ->
    return node.title.text()
}
println collect

//生成xml
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
//langs并不是一个接收闭包的方法而是生成根节点,在闭包中添加子节点
//type:'curren'表示为langs添加type属性,如果仅仅有值代表为节点添加值
builder.langs(type: 'curren') {
    //同样的方式创建language节点
    language(name: 'Android', author: 'Google', 'good')
    language(name: 'Java', author: 'Oracle', 'very good')
    language(name: 'Ios', author: 'Apple') {
        id(1)
    }
}
println writer